/**
 * Created by easy on 15/5/11.
 */
$(document).ready(function () {
    //初始化pullToRefresh
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    var setName = function (name) {
        return name.split(".")[0]
    };
    //初始化OrderPartyRactive
    vars.ractiveOrderPartysList = new Ractive({
        el: "CONTAINER-orderpartys",
        template: "#TEMPLATE-orderpartys",
        data: {ractiveData: []}
    });
    //初始化OrderRactive
    vars.ractiveOrdersList = new Ractive({
        el: "CONTAINER-orders",
        template: "#TEMPLATE-orders",
        data: {
            ractiveData: [], formatDate: function (time, format) {
                return mc.dealTime(parseInt(time), format);
            }, setName: setName
        }
    });
});
(function () {
    vars.currentPage = 1;
    vars.pageSize = 10;
    vars.sellerID = "";
    vars.searchOrderNo = "";
    basic.deviceReady = function () {
        util.getOrderPartys(function () {
            util.getOrders(function () {
                mc.showContent();
                util.syncOrdersData(function () {
                    util.getOrderPartys(util.getOrders);
                })
            })
        });
        mc.saveDataToLocalStorage("dynamicItem", 1, function () {

        }, "app");

        $(".header-search input").on("input", function () {
            vars.searchOrderNo = this.value;
            util.getOrders();
        });
        document.addEventListener('ViewDidAppear', basic.ViewDidAppear, false);
    };
    basic.ViewDidAppear = function () {
        /*util.getOrderPartys(function () {
            util.getOrders(function () {
                util.syncOrdersData(function () {
                    util.getOrderPartys(util.getOrders);
                })
            })
        });*/
        util.getOrders(function () {
            util.syncOrdersData(function () {
                util.getOrderPartys(util.getOrders);
            })
        })
        mc.saveDataToLocalStorage("dynamicItem", 1, function () {
        }, "app");
        $("#orderprocess").hide();
    }
    basic.rightButtonEvent = function () {
        $(".factory-select").focus();
    };
    util.selectFactory = function (touchObj) {
        vars.sellerID = $(touchObj).find("option:selected").val();
        var factoryName = $(touchObj).find("option:selected").text();
        $("#orderParty").html(factoryName);

        mc.saveDataToLocalStorage("selectFactory", vars.sellerID, function () {

        }, "user");
        util.getOrders(function () {
            //mc.showContent();
            util.syncOrdersData(util.getOrders);
        });
        //alert(factoryID+factoryName)
    };
    // 通过订单号获取流程列表
    util.getProcessByOrderId = function (orderid, type) {

        var getProcessByOrderIdCallBack = function (data) {
            //alert(JSON.stringify(data))
            $(".process-listcontainer").empty();
            var submitType = 0;
            var remarkType = 0;
            if (type == "异常") {
                submitType = 1;
                $("#now").html("新增异常");
            } else {
                submitType = 6;
                remarkType = 1;
                $("#now").html("新增备注");
            }
            for (var i = 0; i < data.length; i++) {
                $(".process-listcontainer").append("<div id='" + data[i].jsonPK + "'>" + data[i].processName + "</div>");
                $("#" + data[i].jsonPK).bind("click", {
                    jsonPK: data[i].jsonPK,
                    orderID: orderid,
                    processName: data[i].processName
                }, function (even) {
                    mc.jump("submit.html?submitType=" + submitType + "&objID=" + even.data.jsonPK + "&processName=" + even.data.processName + "&orderID=" + even.data.orderID + (remarkType == 0 ? "" : "&type=" + remarkType), "添加" + type, "SubmitModal");
                });
            }
            if (data.length == 0) {
                $("#process-nodata").show();
            } else {
                $("#process-nodata").hide()
            }
            $("#orderprocess").fadeIn(300);
        }
        service.getOrderProcessData(orderid, getProcessByOrderIdCallBack);
    }
    //同步订单表，备注表数据
    util.syncOrdersData = function (callback) {
        mc.syncData(["QC_ORDER", "QC_ABNORMAL", "QC_REMARK", "QC_PARTY","QC_PROCESS"], callback);
    };
    //下拉刷新（同步数据后 显示列表）
    util.pullToRefresh = function () {
        util.syncOrdersData(function () {
            util.getOrders(pullToRefresh.reset);
        });
    };
    util.getOrderPartys = function (callback) {
        var getOrderPartysCallback = function (data) {
            //alert(JSON.stringify(data))
            mc.getDataFromLocalStorage("selectFactory", function (saveData) {
                if (saveData != null) {
                    for (var i in data) {
                        if(data[i].sellerID == saveData) {
                            $($(".factory-select option")[i]).attr("selected",true);
                            vars.sellerID = saveData;
                            $("#orderParty").html(data[i].sellerName);
                        } else {
                            $("#orderParty").html(data[0].sellerName);
                            vars.sellerID = data[0].sellerID;
                            mc.saveDataToLocalStorage("selectFactory", vars.sellerID, function () {

                            }, "user");
                        }
                    }
                } else if(data.length > 0) {
                    //$($(".factory-select option").first()).select();
                    $("#orderParty").html(data[0].sellerName);
                    vars.sellerID = data[0].sellerID;
                    mc.saveDataToLocalStorage("selectFactory", vars.sellerID, function () {

                    }, "user");
                }
                vars.ractiveOrderPartysList.data.ractiveData = data;
                vars.ractiveOrderPartysList.update("ractiveData");
                if(data.length == 1) {
                    $(".changefactory").html("");
                    $("#CONTAINER-orderpartys").find("select").addClass("disabled");
                }
                //mc.showContent();
                if (callback != undefined) {
                    callback();
                }
            }, "user");

        }
        service.getOrderPartysData(getOrderPartysCallback);
    }

    //获取订单列表
    util.getOrders = function (callback) {
        var getOrdersCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i in data) {
                data[i].orderAttachment = data[i].attachment != undefined && data[i].attachment != null && data[i].attachment != "null" ? JSON.parse(data[i].attachment)[0] : null;
            }
            vars.ractiveOrdersList.data.ractiveData = data;
            vars.ractiveOrdersList.update("ractiveData");
            common.showFirstOrderPhotos(data);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfOrdersList
            };
            common.morePage(optionsForMorePage);
            if (callback != undefined) {
                callback();
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize,
            sellerID: vars.sellerID,
            orderNo: vars.searchOrderNo.replace("'", "")
        };
        service.getOrdersData(options, getOrdersCallback);
    };
    //获取订单列表分页
    util.paginationOfOrdersList = function () {
        var paginationOfOrdersListCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i in data) {
                data[i].orderAttachment = data[i].attachment != undefined && data[i].attachment != null && data[i].attachment != "null" ? JSON.parse(data[i].attachment)[0] : null;
            }
            vars.ractiveOrdersList.data.ractiveData = $.merge(vars.ractiveOrdersList.data.ractiveData, data);
            vars.ractiveOrdersList.update("ractiveData");
            common.showFirstOrderPhotos(data, vars.currentPage);
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfOrdersList
            };
            common.morePage(optionsForMorePage);
        };
        var options = {
            currentPage: vars.currentPage,
            pageSize: vars.pageSize,
            sellerID: vars.sellerID,
            orderNo: vars.searchOrderNo
        };
        service.getOrdersData(options, paginationOfOrdersListCallback)
    };
    util.ajaxStarted = function (ajaxID, matchIDs) {
        util.changeOrderStatus(matchIDs);
    };
    util.ajaxCompleted = function (ajaxID, result, matchIDs) {
        util.changeOrderStatus(matchIDs);
    };
    util.changeOrderStatus = function (matchIDs) {
        var matchIDsArr = matchIDs.split(",");
        for (var i = 0; i < matchIDsArr.length; i++) {
            var execFindStatus = function () {
                var orderID = matchIDsArr[i];
                //alert(orderID)
                var orderItem = document.getElementById(orderID);
                //alert(JSON.stringify(orderItem))
                if (orderItem) {
                    var findOrderStatusCallback = function (data) {
                        //alert(JSON.stringify(data))
                        var abnormalStatus = data[0].abnormalStatus;
                        var processStatus = data[0].processStatus;
                        var remarkStatus = data[0].remarkStatus;
                        if (abnormalStatus == "uploading"
                            || processStatus == "uploading" || remarkStatus == "uploading") {
                            common.changeAjaxBadgeStatus(1, orderItem, 'order', orderID)
                        } else {
                            if (abnormalStatus == "failed" || processStatus == "failed" || remarkStatus == "failed") {
                                common.changeAjaxBadgeStatus(3, orderItem, 'order', orderID)
                            } else {
                                common.changeAjaxBadgeStatus(2, orderItem, 'order', orderID)
                            }
                        }
                    };
                    var SQLOfFindOrderStatus = "SELECT abnormalStatus,processStatus,remarkStatus FROM QC_ORDER WHERE jsonPK = ?;";
                    mc.execSQL(SQLOfFindOrderStatus, [orderID], findOrderStatusCallback);
                }
            };
            execFindStatus()
        }
    };
    util.findThisOrdersFailedTask = function (touchObj, orderID) {
        var sql = "SELECT FCloudDataTransferID FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + orderID + "%' AND FCloudDataTransferState = 'failed'";
        var findThisOrdersFailedTaskCallback = function (data) {
            //alert(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                data[i] = data[i].FCloudDataTransferID;
            }
            common.execUploadAjaxTask(touchObj, data);
        };
        mc.execSQL(sql, [], findThisOrdersFailedTaskCallback);
    };

    util.hideSearchBar = function () {
        $(".header-search input").val('');
        vars.searchOrderNo = "";
        $(".header-search").fadeOut();
        util.getOrders();
    };

    document.addEventListener("searchEvent", function () {
        if($(".header-search").css("display") == "none") {
            $(".header-search").fadeIn();
        } else {
            $(".header-search input").val('');
            vars.searchOrderNo = "";
            $(".header-search").fadeOut();
            util.getOrders();
        }
    });
})();